package com.ziki.bswicket.template.crud.page;

import java.util.List;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.repeater.Item;

import com.ziki.bswicket.action.PopulateAction;
import com.ziki.bswicket.component.BsDataView;
import com.ziki.bswicket.component.BsLink;
import com.ziki.bswicket.page.BsPage;
import com.ziki.bswicket.panel.BsPagingNavigator;
import com.ziki.bswicket.template.base.BaseTemplatePage;
import com.ziki.bswicket.template.crud.model.CrudModel;
import com.ziki.bswicket.template.crud.service.CrudService;
import com.ziki.common.util.string.StrUtil;
import com.ziki.framework.wicket.markup.html.navigation.paging.FwPageable;
import com.ziki.framework.wicket.markup.repeater.data.FwPageableDataProvider;

public class CrudListPage extends BaseTemplatePage implements FwPageable<CrudModel> {
    private static final long serialVersionUID = 1L;

    private BsDataView<CrudModel> dataView;

    private CrudService crudService;

    public CrudListPage() {
        FwPageableDataProvider<CrudModel> data = new FwPageableDataProvider<CrudModel>(this);
        dataView = new BsDataView<CrudModel>("dataView", data, 3);
        dataView.add(getPopulateAction(this));
        add(dataView);
        add(new BsPagingNavigator("navigator", dataView));
    }

    @Override
    public List<CrudModel> getPageList(long first, long count) {
        crudService = new CrudService();
        CrudModel model = new CrudModel();
        return crudService.getPageList(model, first, count);
    }

    @Override
    public long getDataCount() {
        crudService = new CrudService();
        CrudModel model = new CrudModel();
        return crudService.getDataCount(model);
    }

    private PopulateAction<CrudModel> getPopulateAction(final BsPage dataGridPage) {
        return new PopulateAction<CrudModel>() {
            @Override
            public void performPopulate(Item<CrudModel> item) {
                CrudModel article = item.getModelObject();
                long index = item.getIndex() + dataView.getFirstItemOffset() + 1;
                item.add(new Label("num", index));
                item.add(new Label("title", article.getTitle()));
                item.add(new Label("crdate", article.getCrdate()));
                BsLink btnEdit = new BsLink("btnEdit");
                btnEdit.add(CrudEditPage.editActions(StrUtil.parseStr(index - 1), dataGridPage));
                item.add(btnEdit);
            }
        };
    }

}
